import axios from "axios";

const CancelToken = axios.CancelToken;
const httpMap = new Map();
function getHttpKey(config: any) {
  let { url, method, data, params } = config;
  data = isString(data) ? data : JSON.stringify(data);
  params = isString(params) ? params : JSON.stringify(params);
  return `url=${url}&method=${method}&data=${data}&params=${params}`;
}
function addHttp(config: any) {
  const httpKey = getHttpKey(config);
  if (httpMap.has(httpKey)) {
    const source = CancelToken.source();
    config.cancelToken = source.token;
    source.token.reason = {
      message: `【${config.url}】有相同请求未完成，请勿重复请求`
    };
    source.cancel();
  } else {
    httpMap.set(httpKey, true);
  }
}
function removeHttp(config: any) {
  if (config) {
    const httpKey = getHttpKey(config);
    httpMap.delete(httpKey);
  }
}
function clearHttp() {
  httpMap.clear();
}

export { addHttp, removeHttp, clearHttp, axios };
